<?php
namespace Coding\php;
include 'init.php';


use Illuminate\Support\Facades\DB;
use function Co\run;
use Coding\php\lib\MysqlPool;
use Swoole\Coroutine\WaitGroup;
use Swoole\Database\PDOPool;
use Swoole\Database\PDOProxy;
use Swoole\Event;
use \PDO AS PDO;

class Order
{


    public function __construct()
    {
        $pool = MysqlPool::instance();
    }

    /**
     * 模拟并发下单, 造成mysql死锁的现象
     * @var \PDOStatement $statement
     */
    public function createOrder()
    {
        /** @var PDOPool $pool */
        $pool = MysqlPool::instance();
        $wg = new WaitGroup();

        for ($i = 0; $i <= 5000; $i ++) {
            // $wg->add();
            go(function () use ($i, $pool, $wg){
                try {

                    $rawi = $i;
                    /** @var PDO $db */
                    $db = $pool->get();

                    $db->beginTransaction();

                    $statement = $db->exec('update wsa_video set user_id = user_id +1 where id = 5');

                    $db->commit();

                    console_log(sprintf('before i: %s, now i: %s', $rawi, $i));

                    $pool->put($db);
                } catch (\Exception $e) {
                    $db->rollBack();
                    console_log($e->getMessage());
                }
                // $wg->done();
            });
        }
        // $wg->wait();
    }


}

run(function () {

    $order = new Order();

    $order->createOrder();

});

Event::wait();
